package LC05;

/**
 * @author zhangsan
 */
public class LC0443 {
    public static int compress1(char[] chars) {
        int n = chars.length;
        StringBuilder s = new StringBuilder();
        char a = chars[0];
        int b = 1;
        for (int i = 1; i < n; i++) {
            if (a == chars[i]) {
                b++;
            } else {
                s.append(a);
                if (b != 1) {
                    s.append(b);
                }
                a = chars[i];
                b = 1;
            }
        }
        s.append(a);
        if (b != 1) {
            s.append(b);
        }
        char[] sarr = s.toString().toCharArray();
        for (int i = 0; i < sarr.length; i++) {
            chars[i] = sarr[i];
        }
        return s.length();
    }

    public static int compress(char[] chars) {
        int length = chars.length;
        int a = 0, b = 0;
        int idx = a;
        int gap;
        while (b < length) {
            if (chars[a] == chars[b]) {
                b++;
            } else {
                gap = b - a;
                chars[idx++] = chars[a];
                if (gap != 1) {
                    char[] charArray = String.valueOf(gap).toCharArray();
                    for (char c : charArray) {
                        chars[idx++] = c;
                    }
                }
                a = b;
            }
        }
        gap = b - a;
        chars[idx++] = chars[a];
        if (gap != 1) {
            char[] charArray = String.valueOf(gap).toCharArray();
            for (char c : charArray) {
                chars[idx++] = c;
            }
        }
        return idx;
    }

    public static void main(String[] args) {
        System.out.println(compress(new char[]{'a', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'}));
    }
}
